from logging.handlers import RotatingFileHandler
import logging
from flask import Flask, render_template, g
from flask_sqlalchemy import SQLAlchemy
from flask_wtf.csrf import generate_csrf
from redis import StrictRedis
from flask_wtf import CSRFProtect
from flask_session import Session
from config import config, Config
from web_.utils.common import do_index_class, user_login_data

db = SQLAlchemy()  # type:db
strict_redis = None  # type:StrictRedis


def create_app(config_name):
    """通过传入不同的配置名字，初始化其对应配置的应用实例"""
    # 配置项目日志d
    setup_log(config_name)
    app = Flask(__name__)
    app.config.from_object(config[config_name])
    db.init_app(app)
    global strict_redis
    strict_redis = StrictRedis(Config.redis_host, Config.redis_port, decode_responses=True)  # 创建REDIS对象
    # csrf 校验
    CSRFProtect(app)
    # 向COOKING中添加CSRF_TOKEN，每次返回前请求
    app.add_template_filter(do_index_class, 'index_class')

    @app.after_request
    def after_request(response):
        csrf_token = generate_csrf()
        response.set_cookie('csrf_token', csrf_token)
        return response

    # 设置储存路径
    Session(app)
    # 1.蓝图注册
    from web_.modules.index import index_blue
    app.register_blueprint(index_blue)
    # 2.蓝图注册
    from web_.modules.passport import passport_blue
    app.register_blueprint(passport_blue)
    from web_.modules.news import news_blue
    app.register_blueprint(news_blue)
    from web_.modules.profile import profile_blu
    app.register_blueprint(profile_blu)
    from web_.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    # 404
# @app.errorhandler(404)
# @user_login_data
# def page_not_found(_):
#     user = g.user
#     data = {"user_info": user.to_dict() if user else None}
#     return render_template('news/404.html', data=data)
    return app


def setup_log(config_name):
    logging.basicConfig(level=config[config_name].LOG_LEVEL)  # 调试debug级
    # 创建日志记录器，指明日志保存的路径、每个日志文件的最大大小、保存的日志文件个数上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 创建日志记录的格式 日志等级 输入日志信息的文件名 行数 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 为刚创建的日志记录器设置日志记录格式
    file_log_handler.setFormatter(formatter)
    # 为全局的日志工具对象（flask app使用的）添加日志记录器
    logging.getLogger().addHandler(file_log_handler)
